#pragma once
#include <pthread.h>
#include <ctime>
class cond
{
public:
    cond() : _cond(new pthread_cond_t)
    {
        pthread_cond_init(_cond, 0);
    }

    int wait(pthread_mutex_t *mutex)
    {
        return pthread_cond_wait(_cond, mutex);
    }

    int timewait(pthread_mutex_t *mutex, const time_t &ms)
    {
        // 设定倒计时
        struct timespec countdown;
        clock_gettime(CLOCK_REALTIME, &countdown);
        countdown.tv_sec += ms / 1000;        // 设定倒计时秒数
        time_t micro_second = ms % 1000 * 1000; // 设定倒计时除去秒数, 剩余微妙
        countdown.tv_sec += (micro_second + countdown.tv_nsec / 1000) / 1000000;
        countdown.tv_nsec = (micro_second * 1000 + countdown.tv_nsec) % 1000000000;

        return pthread_cond_timedwait(_cond, mutex, &countdown);
    }

    int signal()
    {
        return pthread_cond_signal(_cond);
    }

    int broadcast()
    {
        return pthread_cond_broadcast(_cond);
    }

    ~cond()
    {
        pthread_cond_destroy(_cond);
        delete _cond;
    }

private:
    pthread_cond_t *_cond;
};
